package com.csusm.geo.science.tutor;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

public class ImageSwitcherActivity extends Activity implements
		AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
	private int picPosition;
	Thread mythread;
	private Handler handler = new Handler();
	Gallery g = null;
	Bitmap bmImg;
	boolean isRunning = true;
	boolean stop = false;
	Button btn;
	ArrayList<Bitmap> bmImages = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.slideshow);
		//Get the data from previous activity
		Intent i = getIntent();
		String selLoc = (String) i.getSerializableExtra("SelLoc");
		SlideShowDbhelper slideShowDbhelper = new SlideShowDbhelper();
  		@SuppressWarnings("unchecked")
		ArrayList<String> urlPaths = slideShowDbhelper.getLinks(selLoc);
  		//download images from the url paths
		downloadFile(urlPaths);
		btn = (Button) findViewById(R.id.pause);
		btn.setText("Pause");

		mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
		mSwitcher.setFactory(this);
		mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_in));
		mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out));

		g = (Gallery) findViewById(R.id.gallery);
		g.setAdapter(new ImageAdapter(this));
		g.setOnItemSelectedListener(this);
		mythread = new Thread(runnable);
		mythread.start();
	}

	public void onPauseClick(View v) {
		String temp = btn.getText().toString();
		if (temp.equals("Play")) {
			isRunning = true;
			btn.setText("Pause");
		} else if (temp.equals("Pause")) {
			isRunning = false;
			btn.setText("Play");

		}
	}

	@SuppressWarnings("rawtypes")
	public void onItemSelected(AdapterView parent, View v, int position, long id) {
		// mSwitcher.setImageResource(mImageIds[position]);
		Drawable drawable = new BitmapDrawable(bmImages.get(position));
		mSwitcher.setImageDrawable(drawable);
	}

	private Runnable runnable = new Runnable() {
		public void run() {
			//When Pause button is not clicked
			if (isRunning) {
				myslideshow();
			}
			//run with a delay of 5 seconds
			handler.postDelayed(this, 5000);
		}
	};
	//Slide show image selection
	private void myslideshow() {
		picPosition = g.getSelectedItemPosition() + 1;
		if (picPosition >= bmImages.size()) {
			picPosition = g.getSelectedItemPosition(); // stop
		} else {
			g.setSelection(picPosition);// move to the next gallery element.
		}

	}

	@SuppressWarnings("rawtypes")
	public void onNothingSelected(AdapterView parent) {
	}

	public View makeView() {
		ImageView i = new ImageView(this);
		i.setBackgroundColor(0xFF000000);
		i.setScaleType(ImageView.ScaleType.FIT_CENTER);
		i.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		return i;
	}

	private ImageSwitcher mSwitcher;

	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;

		public ImageAdapter(Context c) {
			mContext = c;

			TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
			mGalleryItemBackground = a.getResourceId(
					R.styleable.Gallery1_android_galleryItemBackground, 0);
			a.recycle();
		}

		public int getCount() {
			return bmImages.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(mContext);
			i.setImageBitmap(bmImages.get(position));
			// i.setImageResource(mImageIds[position]);
			i.setAdjustViewBounds(true);
			i.setLayoutParams(new Gallery.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			i.setBackgroundResource(mGalleryItemBackground);
			return i;
		}

		private Context mContext;

	}
	
	// download all the images
	void downloadFile(ArrayList<String> urls) {
		if (urls != null && !urls.isEmpty()) {
			bmImages = new ArrayList<Bitmap>();
			for (String fileUrl : urls) {
				try {
					//establish a connection
					InputStream is = OpenHttpConnection(fileUrl);
					//get the bitmap image from the stream
					bmImg = BitmapFactory.decodeStream(new FlushedInputStream(
							is));
					bmImages.add(bmImg);
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private InputStream OpenHttpConnection(String urlString) throws IOException {
		InputStream in = null;
		int response = -1;
		URL url = null;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		URLConnection conn = url.openConnection();

		if (!(conn instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");

		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}
		} catch (Exception ex) {
			throw new IOException("Error connecting");
		}
		return in;
	}

	/* An InputStream that skips the exact number of bytes provided, unless it
	 * reaches EOF.
	 */
	static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}
		@Override
		public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int b = read();
					if (b < 0) {
						break; // we reached EOF
					} else {
						bytesSkipped = 1; // we read one byte
					}
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}

}
